<template>
    <div class="setpwd">
        <el-form
          size="small"
          ref="formRef"
          style="max-width: 600px"
          :model="formData"
          status-icon
          :rules="rules"
          label-width="60px"
      >
        
        <el-form-item label="旧密码" prop="oldLoginPassword">
          <el-input v-model="formData.oldLoginPassword" style="width: 300px;"  type="password"/>
        </el-form-item>
        <el-form-item label="新密码" prop="newLoginPassword">
          <el-input v-model="formData.newLoginPassword" style="width: 300px;"  type="password"/>
        </el-form-item>
        <el-form-item label="确认密码" prop="newLoginPassword2">
          <el-input v-model="formData.newLoginPassword2" style="width: 300px;"  type="password"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(formRef)">修改密码</el-button>
          <el-button @click="resetForm(formRef)">取消</el-button>
        </el-form-item>
    
    </el-form>
    </div>
</template>

<script setup lang="ts">
import { ref ,reactive} from "vue";
import type { FormInstance,FormRules } from 'element-plus'
import { $resetPwd } from "../../api/admin";
import {ElNotification} from 'element-plus'
const formRef = ref<FormInstance>()

//表单数据
const formData = ref({
   oldLoginPassword:'',
   newLoginPassword:'',
   newLoginPassword2:''
})

//验证原始密码
const validateOldPassword = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    callback()
  }
}

//验证原始密码
const validatenewLoginPassword = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入新密码'))
  } else {
    callback()
  }
}
const validatenewLoginPassword2 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入重复密码'))
  }else if(value!==formData.value.newLoginPassword){
    callback(new Error('两次密码输入不一致'))
  } else {
    callback()
  }
}

const rules = reactive<FormRules<typeof formData>>({
  oldLoginPassword: [{ validator: validateOldPassword, trigger: 'blur' }],
  newLoginPassword: [{ validator: validatenewLoginPassword, trigger: 'blur' }],  
  newLoginPassword2:  [{ validator:validatenewLoginPassword2,trigger:'blur'}]
})

//提交表单
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async(valid) => {
    if (valid) {
      const ret = await $resetPwd(formData.value);
      if(ret.code === 2001){
        ElNotification({
            title: '成功！',
            message: '恭喜你，更新成功！',
            type: 'success',
        })
      }else{
        ElNotification({
            title: '失败！',
            message: '服务器异常，请联系管理员！',
            type: 'error',
        })
      }
    } else {
      console.log('error submit!')
    }
  })
}

//重置表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

</script>

<style lang="scss" scoped>

</style>